<template>
  <div>
    <Title v-if="!hideTitle" title="订单配置" style="margin-bottom:20px;"/>
    <div v-if="showOrderSetting" class="cost-main" style="margin-top: 24px">
      <!-- 需添加权限 -->
      <orderKindConfig />
    </div>
    <div class="flex-center title-top">
      <Title title="成本项配置" style="font-size:16px;"/>
      <CreateBtn v-if="hasRouteAuth('system:cost:add')" text="添加成本项" @click.native="addCost" />
    </div>
    <el-table
      v-loading="listloading"
      :data="costListData.items"
      :max-height="tableHeight"
      class="fb-table"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      header-cell-class-name="order-data-header-cell"
      fit
      hightlight-current-row>
      <el-table-column align="left" label="成本ID" width="100">
        <template slot-scope="scope">
          <div>{{ scope.row.costId }}</div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="成本项名称" min-width="150">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.costName" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="成本类型" min-width="150">
        <template slot-scope="scope">
          {{ scope.row.costType | costTypeFilter }}
        </template>
      </el-table-column>
      <el-table-column align="left" label="成本来源" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.costBelong || scope.row.costBelong === 0">{{ scope.row.costBelong | costBelongFilter }}</div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="简介" min-width="180px">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.summary" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="成本项可填写0" min-width="120px">
        <template slot-scope="scope">{{ scope.row.canBeZero ? '是' : '否' }}</template>
      </el-table-column>
      <el-table-column align="left" label="创建人" min-width="100px">
        <template slot-scope="scope">
          <CheckUserInfo v-if="scope.row.creatorId" :user-id="scope.row.creatorId" :label="scope.row.creator" />
          <ToolTip v-else :content="scope.row.creator"/>
        </template>
      </el-table-column>
      <el-table-column align="left" label="创建时间" min-width="160px">
        <template slot-scope="scope">
          <span v-if="scope.row.createTime">{{ scope.row.createTime | format('YYYY/MM/DD HH:mm') }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column align="left" label="操作" width="100">
        <template slot-scope="scope">
          <div>
            <el-button :class="{'dividing-line': !scope.row.isDefault}" type="text" @click.native="editCost(scope.row)">
              <div style="font-size:14px;">编辑</div>
            </el-button>
            <el-button v-if="!scope.row.isDefault" type="text" @click.native="deleteItem(scope.row.costId)">
              <div style="font-size:14px;">删除</div>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="display:flex;justify-content:flex-end;margin-top:8px;">
      <el-pagination
        :current-page="page"
        :page-size="perPage"
        :total="costListData.total"
        :page-sizes="[20, 50, 100, 250, 500]"
        :layout="showMobilePage?'total, prev, next, jumper':'total, prev, pager, next, sizes, jumper'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :append-to-body="false"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="order-setting-dialog small-common-dialog-size"
      width="450px">
      <div class="main">
        <Title :title="!isEdit?'新增成本项':'编辑成本项'" font-size="16px" style="margin-bottom:20px;"/>
        <el-form
          ref="configForm"
          :rules="rules"
          :model="queryData"
          label-position="right"
          label-width="100px"
          class="setting-form">
          <el-form-item label="成本项名称" prop="costName" style="margin-bottom: 24px;">
            <el-input
              v-model="queryData.costName"
              :disabled="!!(queryData.isDefault && isEdit)"
              style="font-size: 13px;width:240px;"
              type="text"
              size="small"
              maxlength="20"
              placeholder="请输入成本项名称"/>
          </el-form-item>
          <el-form-item label="成本类型" prop="costType" style="margin-bottom:24px;">
            <el-select
              v-model="queryData.costType"
              :disabled="!!(queryData.isDefault && isEdit)"
              popper-class="global-select-down"
              name="orderType"
              class="width240"
              size="small">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
              <el-option
                :label="'公式计算'"
                :value="5"
                style="display:none;" />
              <el-option
                :label="'--'"
                :value="3"
                style="display:none;" />
            </el-select>
          </el-form-item>
          <el-form-item label="成本来源" prop="costBelong" style="margin-bottom:24px;">
            <el-select
              v-model="queryData.costBelong"
              :disabled="!!(queryData.isDefault && isEdit)"
              popper-class="global-select-down"
              name="orderType"
              class="width240"
              size="small">
              <el-option
                v-for="item in belongOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="成本简介" prop="summary" style="margin-bottom: 24px;">
            <el-input
              v-model="queryData.summary"
              style="font-size: 13px;width:240px;"
              type="text"
              size="small"
              maxlength="100"
              placeholder="请输入成本项简介"/>
          </el-form-item>
          <el-form-item style="margin-bottom: 24px;">
            <el-checkbox v-model="queryData.canBeZero">成本项可填写0</el-checkbox>
          </el-form-item>
        </el-form>
        <div class="btn-container">
          <el-button :loading="loading" type="primary" size="small" @click="handleOk">确定</el-button>
          <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose()">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import orderKindConfig from '@/components/Configuration/orderKindConfig';
import CreateBtn from '@/components/Common/baseComponent/createBtn';
import { costList, addCost, editCost, deleteCost } from '@/api/config';
import { hasRouteAuth } from '@/utils/permission';
import { format } from '@/filters/date';
import { mapState } from 'vuex';

export default {
  components: { Title, orderKindConfig, CreateBtn },
  filters: {
    costTypeFilter(data) {
      const obj = {
        '1': '平台',
        '2': '供应商',
        '4': '分成比例',
        '5': '公式计算'
        // '3': '供应商+含税'
      };
      return obj[data.toString()] || '--';
    },
    costBelongFilter(data) {
      const obj = {
        '0': '渠道订单',
        '1': '项目订单',
        '2': '商务订单',
        '3': '营销授权',
        '4': '电商销售',
        '5': '项目渠道单'
      };
      return obj[data.toString()] || '--';
    },
    format
  },
  props: {
    hideTitle: {
      type: Boolean,
      default: false
    },
    showOrderSetting: {
      type: Boolean,
      default: true
    }
  },
  data() {
    const validateName = (msg) => {
      return (rule, value, callback) => {
        const name = this.queryData.costName;
        if (!name || name === '') { callback(new Error(msg)); } else { callback(); }
      };
    };
    const validateRate = (msg) => {
      return (rule, value, callback) => {
        const taxRate = this.queryData.taxRate;
        if (taxRate || taxRate === 0) { callback(); } else { callback(new Error(msg)); }
      };
    };
    const validateType = (msg, key) => {
      return (rule, value, callback) => {
        const costType = this.queryData[key];
        if (!costType && costType !== 0) { callback(new Error(msg)); } else { callback(); }
      };
    };
    return {
      rules: {
        costName: [{ required: true, trigger: 'blur', validator: validateName('请输入成本项名称') }],
        costType: [{ required: true, trigger: 'change', validator: validateType('请选择成本类型', 'costType') }],
        costBelong: [{ required: true, trigger: 'change', validator: validateType('请选择成本来源', 'costBelong') }],
        taxRate: [{ required: true, trigger: 'blur', validator: validateRate('请输入税率') }]
      },
      costListData: {
        items: []
      },
      page: 1,
      perPage: 20,
      isEdit: false,
      dialogVisible: false,
      loading: false,
      queryData: {
        costName: '',
        costType: 2,
        costBelong: 0,
        summary: '',
        taxRate: '',
        proposerObj: {}
      },
      typeOptions: [
        { label: '供应商', value: 2 },
        { label: '平台', value: 1 },
        { label: '分成比例', value: 4 }
      ],
      belongOptions: [
        { label: '渠道订单', value: 0 },
        { label: '项目订单', value: 1 },
        { label: '商务订单', value: 2 },
        // { label: '营销授权', value: 3 },
        { label: '电商销售', value: 4 },
        { label: '项目渠道单', value: 5 }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableHeight() {
      return window.innerHeight - 222;
    }
  },
  created() {
    this.getCost();
  },
  methods: {
    hasRouteAuth,
    getCost(reset = false) {
      if (reset) this.page = 1;
      this.listloading = true;
      costList({ page: this.page, perPage: this.perPage }).then(res => {
        this.listloading = false;
        if (res.code === 200) {
          this.costListData = res.data;
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.listloading = false;
      });
    },
    addCost() {
      this.isEdit = false;
      this.dialogVisible = true;
      if (this.$refs.configForm) this.$refs.configForm.clearValidate();// 清空校验
    },
    editCost(item) {
      if (this.$refs.configForm) this.$refs.configForm.clearValidate(); // 清空校验
      this.queryData = JSON.parse(JSON.stringify(item));
      const proposerObj = {// 3.0.2新增申请人
        id: item.proposerId,
        userName: item.proposer
      };
      this.$set(this.queryData, 'proposerObj', proposerObj);
      this.queryData.costType = Number(this.queryData.costType);
      this.isEdit = true;
      this.dialogVisible = true;
    },
    handleOk() {
      this.$refs.configForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.edit();
          } else {
            this.add();
          }
        } else {
          return false;
        }
      });
    },
    add() {
      this.loading = true;
      const params = this.queryData;
      addCost(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('新增成功');
          this.handleClose();
          this.getCost();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        console.log(err);
        this.loading = false;
      });
    },
    edit() {
      this.loading = true;
      const params = this.queryData;
      editCost(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.handleClose();
          this.getCost();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        console.log(err);
        this.loading = false;
      });
    },
    deleteItem(id) {
      this.$confirm('是否确定删除该成本？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        deleteCost({ id }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.costListData.total) {
              this.page--;
            }
            this.getCost();
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.queryData = { costName: '', costType: 2, costBelong: 0 };
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getCost(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getCost();
    }
  }
};
</script>

<style lang="scss" scoped>
@import url('./common.scss');
.title-top {
  margin-bottom: 16px;
}
.btn-container {
  display: flex;
  justify-content: center;
}
.width240 {
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
.cost-main {
  display: flex;
  padding-left: 13px;
  align-items: center;
}
.dividing-line {
  position: relative;
  &::before {
    content: '';
    position: absolute;
    right: -9px;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
</style>
<style lang="scss">
.cost-config-dialog {
  .el-dialog {
    width: 800px !important;
  }
}
</style>
